package com.dy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dy.common.R;
import com.dy.constants.EmployeeConstants;
import com.dy.entity.Employee;
import com.dy.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/**
 * ClassName:EmployeeController
 * Package:com.dy.controller
 * Description:
 *
 * @Date:2022/8/3 16:13
 * @Author:dy
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * @Author dy
     * @Description: 后台员工登录验证
     */
    @PostMapping("/login")
    public R employeeLogin(@RequestBody Employee emp, HttpSession session){
        //根据name 查询是否存在
        Employee oneEmp = employeeService.getOne(
                new LambdaQueryWrapper<Employee>().eq(Employee::getUsername,emp.getUsername()));

        //查询不到 用户名错误
        if(oneEmp == null){
            return R.error("登录失败！");
        }
        //提交密码  MD5加密
        String passMd5 = DigestUtils.md5DigestAsHex(emp.getPassword().getBytes());
        if(!oneEmp.getPassword().equals(passMd5)){
            //密码不一致；
            return R.error("密码错误!");
        }

        //判断员工状态
        if(oneEmp.getStatus() != 1){ //1:账号状态正常
            return R.error("账号暂被禁用！");
        }
        // 登录成功   session 存入员工 ID
        session.setAttribute("employee",oneEmp.getId());
        return R.success(oneEmp) ;
    }

    /**
     * @Author dy
     * @Description: 员工退出
     */
    @PostMapping("/logout")
    public R<String> employeeLogout(HttpSession session){
        //清除session 员工数据
        session.removeAttribute("employee");
        return R.success("退出成功！");
    }

    /**
     * @Author dy
     * @Description: 新增员工
     */
    @PostMapping
    public R<String> save(@RequestBody Employee employee, HttpSession session){
        try {
            //查询用户名 是否存在
            LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<Employee>();
            queryWrapper.eq(Employee::getUsername,employee.getUsername());
            Employee one = employeeService.getOne(queryWrapper);
            if(one != null){
                return R.error("["+one.getUsername()+"]已经存在，请重新输入。");
            }
            //设置密码(默认)
            employee.setPassword(DigestUtils.md5DigestAsHex(EmployeeConstants.DEFAULT_PASSWORD.getBytes()));

            //设置创建和修改时间
            //employee.setCreateTime(LocalDateTime.now());
            //employee.setUpdateTime(LocalDateTime.now());

            //设置 创建和修改用户的 用户ID
            //Long empId = (Long) session.getAttribute("employee");
            //employee.setCreateUser(empId);
            // employee.setUpdateUser(empId);
            //新增员工
            employeeService.save(employee);
            return R.success("创建成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("新增员工失败。");
        }
    }

    /**
     * @Author dy
     * @Description: 查询员工 信息（带分页）
     */
    @GetMapping("/page")
    public R<Page> page(Integer page,Integer pageSize,String name){
        Page pageInfo = new Page(page, pageSize);

        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        //加入名字过滤条件
        queryWrapper.like(StringUtils.isNoneBlank(name),Employee::getName,name);
        //加入排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);

        employeeService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }

    /**
     * @Author dy
     * @Description:  修改员工的 状态
     *
     * * @return R<String>
     */
    @PutMapping
    public R<String> update(@RequestBody Employee employee,HttpSession session){
        //employee.setUpdateTime(LocalDateTime.now());
        // employee.setUpdateUser((Long)session.getAttribute("employee"));
        employeeService.updateById(employee);
        return R.success("修改成功");
    }


    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        log.info("根据ID查询员工信息");
        Employee emp = employeeService.getById(id);
        return R.success(emp);
    }


}
